package cn.pinming.chyn.tools.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.date.DateUtil;
import cn.pinming.chyn.tools.annotations.ExportColumn;
import cn.pinming.chyn.tools.exception.ChynException;
import cn.pinming.chyn.tools.exception.ChynResultCode;

public class ExcelDownloadUtil {

	public static void export(HttpServletRequest request, HttpServletResponse response, List<?> datas, Class clazz) {

		ExportColumn exportType = (ExportColumn) clazz.getAnnotation(ExportColumn.class);
		if (exportType == null) {
			throw new ChynException(ChynResultCode.ERR, "class未设置ExportColumn");
		}
		String str = exportType.name();

		Map<Integer, Field> fieldMap = new HashMap<>();
		Field[] fields = clazz.getDeclaredFields();
		int maxIndex = 0;
		for (Field f : fields) {
			ExportColumn exportField = (ExportColumn) f.getAnnotation(ExportColumn.class);
			if (exportField == null) {
				continue;
			}
			int index = exportField.index();
			if (fieldMap.get(index) != null) {
				throw new ChynException(ChynResultCode.ERR, "field index冲突 ：" + index);
			}
			fieldMap.put(index, f);
			maxIndex = Math.max(maxIndex, index);
		}

		maxIndex++;
		// 定义列
		LinkedHashMap<String, String> columnMap = new LinkedHashMap<String, String>();
		for (int i = 0; i < maxIndex; i++) {
			Field f = fieldMap.get(i);
			if (f == null) {
				continue;
			}
			ExportColumn exportField = (ExportColumn) f.getAnnotation(ExportColumn.class);
			if (exportField == null) {
				continue;
			}
			columnMap.put(exportField.name(), f.getName());
		}

		// 封装数据
		List<Map<String, Object>> dataList = new ArrayList<>();
		if (datas != null && !datas.isEmpty()) {
			for (int i = 0; i < datas.size(); i++) {
				Object bean = datas.get(i);
				if (bean == null) {
					continue;
				}
				JSONObject jsonObject = (JSONObject) JSONObject.toJSON(bean);
				Map<String, Object> data = new HashMap<>();
				for (int j = 0; j < maxIndex; j++) {
					Field f = fieldMap.get(j);
					if (f == null) {
						continue;
					} 
					ExportColumn exportField = (ExportColumn) f.getAnnotation(ExportColumn.class);
					if (exportField == null) {
						continue;
					}

					if (exportField.pk()) {
						data.put(f.getName(), i + 1);
					} else {
						String value = "";
						if (f.getType().equals(Date.class)) {
							Date date = jsonObject.getDate(f.getName());
							value = DateUtil.format(date, exportField.format());
						} else {
							value = jsonObject.getString(f.getName());
						}
						data.put(f.getName(), value);
					}

				}
				dataList.add(data);
			}
		}

		ExcelUtil.download(dataList, columnMap, str, str, request, response, true);
	}

}
